/* Standard C libraries */
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>

#include <string>
#include <sstream>

#include "Master_Socket.h"
#include "../Socket/SocketException.h"

//#define QUTGS01 "131.181.106.126"
#define QUTGS01 "131.181.106.126"

using namespace std;

int main(int argc, char *argv[])
{
	string message;
	unsigned int port = 50000;
	unsigned int new_port = 0;

	fprintf(stderr, "Connecting to Master on %s\n",QUTGS01);

	try
	{
		MasterSocket master_server;
		master_server.Initialise(QUTGS01,port);
		fprintf(stderr, "Connected on port: %u\n",port);
		master_server >> message;
		new_port = atoi(message.c_str()); 
		if (port == 0)
		{	
			fprintf(stderr, "Maximum number of connections reached. Exiting.\n");
			return 0;
		}		
		fprintf(stderr, "Reconnecting on port: %u\n", new_port);
		master_server.Initialise(QUTGS01,new_port);				
		fprintf(stderr, "Reconnected on port: %u\n",new_port);
		
		fprintf(stdout, "%% System Time : gSpeak Time : X1 : Y1 : Z1 : NX1 : NY1 : NZ1 : OX1 : OY1 : OZ1 : X2 : Y2 : Z2 : NX2 : NY2 : NZ2 : OX2 : OY2 : OZ2\n");
		while (true)
		{
			master_server >> message;
			fprintf(stdout, "%s\n",message.c_str());
		}
	}
	catch ( SocketException& e) 
	{
		fprintf(stderr, "Exception was caught\n%s\nExiting.\n",e.description().c_str());
	}
}
